<script setup la lang="ts">
import { getCouponListApi, receiveCouponApi } from '@/api/coupon'
import type { couponListItem } from '@/types/coupon'
import useZPaging from '@/uni_modules/z-paging/components/z-paging/js/hooks/useZPaging'
import { ref } from 'vue'
import { onLoad, onPageScroll, onReachBottom, onShow } from '@dcloudio/uni-app'
import { onShowRefreshData } from '@/utils/common'

const couponList = ref<couponListItem[]>([])
const paging = ref()
useZPaging(paging)
const queryList = async (page: number, page_size: number) => {
  const res = await getCouponListApi({
    page,
    page_size,
  })
  paging.value.complete(res.result.data)
}

const handleButtonClicked = (item: couponListItem) => {
  receiveCouponApi(item.id).then((res) => {
    if (res.result.id) {
      paging.value.refresh()
      setTimeout(() => {
        uni.showToast({
          title: 'Claimed successfully',
          icon: 'success',
        })
      }, 500)
    }
  })
}

onShowRefreshData(() => {
  paging.value?.refresh()
})
</script>

<template>
  <z-paging ref="paging" v-model="couponList" @query="queryList">
    <shop-coupon
      v-if="couponList.length > 0"
      :couponList="couponList"
      mode="center"
      buttonTitle="Collect"
      @buttonClicked="handleButtonClicked"
    />
  </z-paging>
</template>

<style lang="scss" scoped></style>
